<template>
  <div>
    <el-container>
      <el-aside width="200px"></el-aside>

      <el-main>
        <!-- 活动的截止日期和标题 -->
        <el-row>
          <el-card :body-style="{ padding: '0px' }" class="custom-card">
            <div class="image-container">
              <img
                :src="backgroundImage"
                class="image"
                @error="handleImageError"
              />
              <div class="overlay">
                <div class="overlay-content">
                  <div class="title">{{ activity.title }}</div>
                  <div class="tag">ACTIVITY</div>
                  <!-- 添加删除按钮 -->
                  <div
                    v-if="isCreator || isAdmin"
                    class="delete-button"
                    @click.stop="showDeleteConfirm"
                  >
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="time-left">
                <span>{{ activity.end_time }}</span>
                <span>days left</span>
              </div>
              <!-- 添加点赞按钮和数量 -->
              <div class="like-container" @click="handleLike">
                <i :class="[activityDetail?.isLiked ? 'el-icon-thumb' : 'el-icon-thumb', 'like-icon', {'liked': activityDetail?.isLiked}]"></i>
                <span class="like-count">{{ likeCount }}</span>
              </div>
              <div class="buttons">
                <el-button type="primary" class="participate-button"
                  >PARTICIPATE</el-button
                >
                <el-button class="view-entries-button">VIEW ENTRIES</el-button>
              </div>
            </div>
          </el-card>
        </el-row>

        <!-- 活动的介绍 -->
        <el-row>
          <el-card class="description-card">
            <div
              class="description-container"
              :class="{ expanded: isExpanded }"
            >
              <div
                class="description-content"
                v-html="activity.description"
              ></div>
              <div class="description-fade" v-if="!isExpanded"></div>
            </div>
            <div class="read-more-button" @click="toggleCardHeight">
              <span>{{ isExpanded ? "收起内容" : "展开全文" }}</span>
              <i
                :class="isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </div>
          </el-card>
        </el-row>

        <!-- 评论区域 -->
        <el-row>
          <el-card class="card-container">
            <Comment
              :activity-id="currentActivityId"
              :comments.sync="comments"
            />
            <div class="pagination-container">
              <el-pagination
                @current-change="handlePageChange"
                :current-page="commentPagination.page"
                :page-size="commentPagination.size"
                :total="commentPagination.total"
                layout="prev, pager, next"
              >
              </el-pagination>
            </div>
          </el-card>
        </el-row>
      </el-main>

      <el-aside width="200px"></el-aside>
    </el-container>
    <el-dialog title="确认删除" :visible.sync="dialogVisible" width="30%">
      <span>确定要删除这个活动吗？此操作不可恢复。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Card from "@/components/Card.vue";
import { 
  fetchGetRequest, 
  getComments, 
  deleteActivity, 
  toggleActivityLike,
  fetchActivityDetail
} from "@/api/api";
import Idea from "@/components/IdeaList.vue";
import Comment from "@/components/comment.vue";
import apiClient from "@/api/api";
import { getRole } from "@/api/auth";

export default {
  data() {
    return {
      currentDate: new Date(),
      isExpanded: false,
      activities: [],
      activeIndex: "",
      activity: "",
      posts: [],
      comments: [],
      backgroundImage: "",
      dialogVisible: false,
      userInfo: null,
      commentPagination: {
        page: 1,
        size: 5,
        total: 0,
      },
      isLiked: false,
      likeCount: 0,
      loading: false,
    };
  },
  computed: {
    currentActivityId() {
      return this.$route.query.id;
    },
    isAdmin() {
      return getRole() === "admin";
    },
    isCreator() {
      return this.userInfo && this.activity.createdBy === this.userInfo.userId;
    },
  },
  async mounted() {
    await this.loadData();
    this.fetchUserInfo();
  },
  methods: {
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await apiClient.get("/user/info");
        this.userInfo = response.data;
      } catch (error) {
        console.error("获取用户信息失败:", error);
        this.userInfo = null;
      }
    },
    // 显示删除确认对话框
    showDeleteConfirm() {
      this.dialogVisible = true;
    },
    // 处理删除确认
    async handleDelete() {
      try {
        await deleteActivity(this.currentActivityId);
        this.$message.success("删除成功", 20);
        this.$router.push({ path: "/Idea" });
      } catch (error) {
        console.error("删除失败:", error);
        this.$message.error("删除失败，请重试");
      }
      this.dialogVisible = false;
    },
    async loadData() {
      try {
        this.loading = true;
        
        // 1. 优先从路由参数获取活动ID，其次从localStorage获取
        let activityId = this.$route.query.id;
        if (!activityId) {
          activityId = localStorage.getItem('activityId');
        }
        
        if (!activityId) {
          console.error('无法获取活动ID');
          this.$message.error('获取活动详情失败');
          return;
        }

        console.log('正在获取活动详情，活动ID:', activityId);
        
        // 2. 先尝试直接获取活动详情
        const activityDetail = await fetchActivityDetail(activityId);
        
        if (!activityDetail) {
          console.error('获取活动详情返回为空');
          this.$message.error('获取活动详情失败');
          return;
        }

        console.log('活动详情数据:', activityDetail);
        
        // 3. 更新UI数据
        this.activity = activityDetail;
        this.activityDetail = activityDetail;
        
        // 处理点赞信息 - 兼容不同的字段名
        // 优先判断 isLiked，然后是 liked
        const isLiked = activityDetail.isLiked !== undefined 
          ? activityDetail.isLiked 
          : (activityDetail.liked !== undefined ? activityDetail.liked : false);
        
        // 优先使用likesCount, 其次是likeCount，然后是likedCount，最后是count
        const likeCount = activityDetail.likesCount !== undefined 
          ? activityDetail.likesCount 
          : (activityDetail.likeCount !== undefined ? activityDetail.likeCount 
            : (activityDetail.likedCount !== undefined ? activityDetail.likedCount : 
              (activityDetail.count !== undefined ? activityDetail.count : 0)));
        
        // 设置点赞状态
        this.isLiked = isLiked;
        this.likeCount = likeCount;
        
        // 记录日志
        console.log('解析的点赞信息:', { isLiked: this.isLiked, likeCount: this.likeCount });
        console.log('原始点赞数据:', {
          isLiked: activityDetail.isLiked,
          liked: activityDetail.liked,
          likesCount: activityDetail.likesCount,
          likeCount: activityDetail.likeCount,
          likedCount: activityDetail.likedCount,
          count: activityDetail.count
        });
        
        // 确保activityDetail对象也有正确的点赞状态
        if (this.activityDetail) {
          this.activityDetail.isLiked = isLiked;
          this.activityDetail.liked = isLiked;
          this.activityDetail.likesCount = likeCount;
          this.activityDetail.likeCount = likeCount;
          this.activityDetail.likedCount = likeCount;
          this.activityDetail.count = likeCount;
        }
        
        // 获取评论数据
        this.fetchComments();
        
        // 更新背景图片
        if (activityDetail.coverUrl || activityDetail.imageUrl) {
          this.updateImage(activityDetail.coverUrl || activityDetail.imageUrl);
        } else {
          this.loadBackgroundImage();
        }
        
      } catch (error) {
        console.error('加载活动详情出错:', error);
        this.$message.error('获取活动详情失败');
      } finally {
        this.loading = false;
      }
    },
    toggleCardHeight() {
      this.isExpanded = !this.isExpanded;
    },

    handleSelect(key) {
      this.$router.push({ path: "/", query: { key: key } });
    },
    async fetchActivityById(id) {
      try {
        console.log('获取活动id是', id);
        const res = await fetchGetRequest(`/activities/${id}`);
        this.activity = res;
      } catch (err) {
        console.log("根据id获取activity错误", err);
      }
    },
    async fetchComments() {
      try {
        // 获取活动ID
        const activityId = this.$route.query.id || localStorage.getItem('activityId') || this.activityDetail?.id || this.activityDetail?.activityId;
        if (!activityId) {
          console.error('获取评论失败: 无法获取活动ID');
          this.$message.error('获取评论失败');
          return;
        }
        
        console.log('获取评论列表，活动ID:', activityId, '页码:', this.commentPagination.page, '每页条数:', this.commentPagination.size);

        const { list, total } = await getComments(
          activityId,
          this.commentPagination.page,
          this.commentPagination.size
        );

        if (!list || list.length === 0) {
          this.comments = [];
          this.commentPagination.total = 0;
          this.$message.info("暂无评论");
          return;
        }
        
        console.log('获取到评论列表:', list.length, '条，总数:', total);
        
        // 确保每个评论对象都包含必要的字段
        this.comments = list.map((comment) => ({
          ...comment,
          likes: comment.likes || 0,
          isLiked: comment.isLiked || false,
          replies: (comment.replies || []).map((reply) => ({
            ...reply,
            userAvatar:
              reply.userAvatar ||
              "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
          })),
        }));

        this.commentPagination.total = total;
      } catch (error) {
        console.error("获取评论列表失败:", error);
        if (error.response?.status === 404) {
          this.$message.info("暂无评论");
        } else {
          this.$message.error("获取评论列表失败");
        }
        this.comments = [];
        this.commentPagination.total = 0;
      }
    },
    handlePageChange(page) {
      this.commentPagination.page = page;
      this.fetchComments();
    },

    handleImageError(e) {
      // 如果是HTTPS链接，尝试转换为HTTP
      if (this.backgroundImage.startsWith("https://")) {
        const httpUrl = this.backgroundImage.replace("https://", "http://");
        e.target.src = httpUrl;
      } else {
        // 如果已经是HTTP或其他类型的链接，使用默认图片
        e.target.src = require("@/assets/images/default-king.png");
      }
    },

    loadBackgroundImage() {
      const defaultImg = require("@/assets/images/default-king.png");
      const url =
        this.activity.imageUrl && this.activity.imageUrl.trim()
          ? this.activity.imageUrl
          : defaultImg;
      this.backgroundImage = url;
    },

    // 处理点赞操作
    async handleLike() {
      try {
        // 获取活动ID - 优先使用activityDetail.id，其次使用activityDetail.activityId，最后使用路由参数
        const activityId = this.activityDetail?.id || this.activityDetail?.activityId || this.$route.query.id;
        
        if (!activityId) {
          console.error('点赞操作 - 无法获取活动ID:', this.activityDetail);
          this.$message.error('操作失败');
          return;
        }
        
        console.log('点赞操作 - 活动ID:', activityId);
        
        // 调用API进行点赞操作
        const result = await toggleActivityLike(activityId);
        console.log('点赞操作结果:', result);
        
        if (!result) {
          console.error('点赞操作返回为空');
          this.$message.error('操作失败');
          return;
        }
        
        // 更新组件状态 - 兼容不同的字段名
        const newLikedStatus = result.liked !== undefined ? result.liked : 
                          (result.isLiked !== undefined ? result.isLiked : !this.isLiked);
                          
        const newLikeCount = result.likesCount !== undefined ? result.likesCount :
                        (result.count !== undefined ? result.count : 
                        (result.likeCount !== undefined ? result.likeCount : 
                        (result.likedCount !== undefined ? result.likedCount : 
                        (newLikedStatus ? this.likeCount + 1 : Math.max(0, this.likeCount - 1)))));
        
        // 更新状态
        this.isLiked = newLikedStatus;
        this.likeCount = newLikeCount;
        
        // 更新activityDetail对象中的点赞信息
        if (this.activityDetail) {
          this.activityDetail.isLiked = newLikedStatus;
          this.activityDetail.liked = newLikedStatus;
          this.activityDetail.likesCount = newLikeCount;
          this.activityDetail.likeCount = newLikeCount;
          this.activityDetail.likedCount = newLikeCount;
          this.activityDetail.count = newLikeCount;
        }
        
        // 缓存点赞状态
        localStorage.setItem(`activity_${activityId}_liked`, this.isLiked.toString());
        
        // 用户反馈
        this.$message.success(this.isLiked ? '点赞成功' : '已取消点赞');
        
      } catch (error) {
        console.error('点赞操作失败:', error);
        this.$message.error('操作失败');
      }
    },
    // 更新背景图片
    updateImage(url) {
      if (!url) {
        this.backgroundImage = require("@/assets/images/default-king.png");
        return;
      }
      
      // 处理HTTPS URL
      if (url.startsWith("https://")) {
        url = url.replace("https://", "http://");
      }
      
      const img = new Image();
      const defaultImg = require("@/assets/images/default-king.png");
      
      img.onload = () => {
        this.backgroundImage = url;
      };
      
      img.onerror = () => {
        console.error("图片加载失败:", url);
        this.backgroundImage = defaultImg;
      };
      
      img.src = url;
      this.backgroundImage = defaultImg; // 默认先显示
    },
  },
  watch: {
    activity: {
      handler() {
        this.loadBackgroundImage();
      },
      immediate: true,
    },
  },
  components: {
    Card,
    Idea,
    Comment,
  },
};
</script>

<style scoped>
.home,
.header,
.el-menu {
  margin: 0;
  padding: 0;
  font-family: "Cera-Bold", sans-serif;
}
.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
}
.spacer {
  height: 60px;
}
.el-menu-demo {
  margin: 0;
}

.custom-card {
  position: relative;
  width: 100%;
  height: 300px;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 2rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
  transition: transform 0.3s ease;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 20px;
}

.overlay-content {
  max-width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.title {
  font-size: 36px;
  font-weight: bold;
  margin-top: 20px;
  font-family: "Cera-Bold", sans-serif;
  letter-spacing: 0.5px;
}

.tag {
  background: red;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  margin-bottom: auto;
}

h1 {
  font-size: 24px;
  margin-bottom: 20px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: auto;
}

.time-left {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 20px;
}

.buttons {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.participate-button {
  background-color: #f0c040;
  border-color: #f0c040;
}

.view-entries-button {
  border-color: #000;
}

.box-card {
  width: 100%;
  overflow: hidden;
  position: relative;
  margin-top: 20px;
  border-radius: 10px;
}

.card-content {
  padding: 20px;
}

.read-more {
  position: relative;
  bottom: 10px;
  right: 20px;
  cursor: pointer;
  color: #409eff;
}

.card-container {
  width: 100%;
  overflow: hidden;
  position: relative;
  margin: 2rem 0;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 2rem;
}

.card {
  margin: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 2rem 0;
  padding: 1rem 0;
  border-top: 1px solid #ebeef5;
  font-family: "Cera-Bold", sans-serif;
}

.description-card {
  width: 100%;
  margin: 2rem 0;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.description-container {
  position: relative;
  max-height: 200px;
  overflow: hidden;
  transition: max-height 0.5s ease;
}

.description-container.expanded {
  max-height: 2000px;
}

.description-content {
  padding: 2rem;
  font-family: "Cera-Bold", sans-serif;
  line-height: 1.6;
}

.description-fade {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  background: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0),
    rgba(255, 255, 255, 1)
  );
  pointer-events: none;
}

.read-more-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
  cursor: pointer;
  color: #409eff;
  font-weight: 500;
  border-top: 1px solid #ebeef5;
  transition: background-color 0.3s;
}

/* .read-more-button:hover {
  background-color: #f5f7fa;
} */

.read-more-button i {
  margin-left: 5px;
}

.delete-button {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 40px;
  height: 40px;
  background-color: rgba(0, 0, 0, 0.75);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.delete-button i {
  color: white;
  font-size: 20px;
  transition: transform 0.3s ease;
}

.delete-button:hover {
  background-color: rgba(245, 108, 108, 1);
  transform: scale(1.15);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4);
}

.delete-button:hover i {
  transform: rotate(12deg);
}

/* 点赞样式 */
.like-container {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 15px;
  transition: all 0.3s ease;
}

.like-container:hover {
  transform: scale(1.1);
}

.like-icon {
  font-size: 20px;
  color: #909399;
  margin-right: 5px;
  transition: all 0.3s ease;
  transform: scale(1);
}

.like-icon.liked {
  color: #FF4949;
  transform: rotate(0deg) scale(1.2);
}

.like-container:hover .like-icon:not(.liked) {
  color: #FF4949;
  opacity: 0.7;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
}
</style>
